package service

import (
	"context"
	"github.com/shopspring/decimal"
	"insighttracking/query/bo"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"time"
)

type _pickingService struct{}

func (s _pickingService) CreateRecordApi(ctx context.Context, tx *dao.QueryTx, req *model.PickingRecordEntity) (err error) {
	return tx.PickingRecordEntity.WithContext(ctx).Create(req)
}

func (s _pickingService) GetRecordApi(ctx context.Context, productionPlanDetailID int64) (resp []*model.PickingRecordEntity, err error) {
	return dao.PickingRecordEntity.WithContext(ctx).Where(dao.PickingRecordEntity.ProductionDetailID.Eq(productionPlanDetailID)).Find()
}

func (s _pickingService) GetScanInfoApi(ctx context.Context, enterpriseID int64, batchNumber string) (resp *bo.ShelfInventoryEntity, err error) {
	err = dao.SpuShelfGridInventoryEntity.WithContext(ctx).
		Select(dao.SpuShelfGridInventoryEntity.ALL, dao.SpuEntity.Name.As("SpuName"), dao.ShelfEntity.Code.As("ShelfCode")).
		LeftJoin(dao.SpuEntity, dao.SpuEntity.ID.EqCol(dao.SpuShelfGridInventoryEntity.SpuID)).
		LeftJoin(dao.ShelfEntity, dao.ShelfEntity.ID.EqCol(dao.SpuShelfGridInventoryEntity.ShelfID)).
		Where(
			dao.SpuShelfGridInventoryEntity.BatchNumber.Eq(batchNumber),
			dao.SpuShelfGridInventoryEntity.EnterpriseID.Eq(enterpriseID),
		).Scan(&resp)
	return
}

func (s _pickingService) GetTaskApi(ctx context.Context, enterpriseID int64, produceDate time.Time) (resp []*model.PickingTaskEntity, err error) {
	return dao.PickingTaskEntity.WithContext(ctx).Where(
		dao.PickingTaskEntity.ProduceDate.Eq(produceDate),
		dao.PickingTaskEntity.EnterpriseID.Eq(enterpriseID),
	).Find()
}

func (s _pickingService) GetPickingCount(ctx context.Context, productionDetailID, spuID int64) (count decimal.Decimal, err error) {
	err = dao.PickingRecordEntity.WithContext(ctx).Select(dao.PickingRecordEntity.PickingCount.Sum()).Where(
		dao.PickingRecordEntity.ProductionDetailID.Eq(productionDetailID),
		dao.PickingRecordEntity.SpuID.Eq(spuID)).Pluck(dao.PickingRecordEntity.PickingCount, &count)
	return
}

var PickingService = _pickingService{}
